#pragma once
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdint.h>
#include <string>
#include <string.h>
#include "Common.hpp"

class InetAddr
{
private:
    void PortNet2Host()
    {
        _port = ::htons(_inet_addr.sin_port);
    }
    void IpNet2Host()
    {
        char inbuffer[64];
        const char *ip = ::inet_ntop(AF_INET, &_inet_addr.sin_addr, inbuffer, sizeof(inbuffer));
        (void)ip;
        _ip = inbuffer;
    }

public:
    InetAddr()
    {
    }
    InetAddr(uint16_t port)
        : _port(port), _ip("")
    {
        _inet_addr.sin_family = AF_INET;
        _inet_addr.sin_port = ::htons(_port);
        _inet_addr.sin_addr.s_addr = INADDR_ANY;
    }

    InetAddr(struct sockaddr_in &addr)
        : _inet_addr(addr)
    {
        PortNet2Host();
        IpNet2Host();
    }

    bool operator==(const InetAddr &addr)
    {
        return _ip == addr._ip && _port == addr._port;
        // return _ip == addr._ip;
    }

    struct sockaddr *NetAddr()
    {
        return CONV(&_inet_addr);
    }

    std::string Ip()
    {
        return _ip;
    }

    uint16_t Port()
    {
        return _port;
    }

    std::string Addr()
    {
        return Ip() + ":" + std::to_string(Port());
    }

    socklen_t NetAddrLen()
    {
        return sizeof(_inet_addr);
    }

    void SetAddr(const sockaddr_in& client, socklen_t &len)
    {
        _inet_addr = client;
        (void)len;

        IpNet2Host();
    }
private:
    struct sockaddr_in _inet_addr;
    std::string _ip;
    uint16_t _port;
};